using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using HuaRongDaoGame.Models;

namespace HuaRongDaoGame.Services
{
    /// <summary>
    /// 动画服务
    /// </summary>
    public class AnimationService
    {
        private Timer animationTimer;
        private List<Animation> activeAnimations;
        private Control targetControl;

        /// <summary>
        /// 动画完成事件
        /// </summary>
        public event EventHandler<AnimationCompletedEventArgs> AnimationCompleted;

        /// <summary>
        /// 构造函数
        /// </summary>
        public AnimationService(Control targetControl)
        {
            this.targetControl = targetControl;
            this.activeAnimations = new List<Animation>();
            
            this.animationTimer = new Timer();
            this.animationTimer.Interval = 16; // ~60 FPS
            this.animationTimer.Tick += AnimationTimer_Tick;
        }

        /// <summary>
        /// 开始方块移动动画
        /// </summary>
        public void AnimateBlockMove(Block block, int targetX, int targetY, int duration = 300)
        {
            var animation = new BlockMoveAnimation(block, targetX, targetY, duration);
            StartAnimation(animation);
        }

        /// <summary>
        /// 开始方块选择动画
        /// </summary>
        public void AnimateBlockSelect(Block block, int duration = 200)
        {
            var animation = new BlockSelectAnimation(block, duration);
            StartAnimation(animation);
        }

        /// <summary>
        /// 开始胜利动画
        /// </summary>
        public void AnimateVictory(int duration = 2000)
        {
            var animation = new VictoryAnimation(duration);
            StartAnimation(animation);
        }

        /// <summary>
        /// 开始动画
        /// </summary>
        private void StartAnimation(Animation animation)
        {
            activeAnimations.Add(animation);
            
            if (!animationTimer.Enabled)
            {
                animationTimer.Start();
            }
        }

        /// <summary>
        /// 动画定时器事件
        /// </summary>
        private void AnimationTimer_Tick(object sender, EventArgs e)
        {
            bool hasActiveAnimations = false;
            var completedAnimations = new List<Animation>();

            foreach (var animation in activeAnimations)
            {
                animation.Update(animationTimer.Interval);
                
                if (animation.IsCompleted)
                {
                    completedAnimations.Add(animation);
                    OnAnimationCompleted(animation);
                }
                else
                {
                    hasActiveAnimations = true;
                }
            }

            // 移除已完成的动画
            foreach (var animation in completedAnimations)
            {
                activeAnimations.Remove(animation);
            }

            // 如果没有活动动画，停止定时器
            if (!hasActiveAnimations)
            {
                animationTimer.Stop();
            }

            // 重绘控件
            if (targetControl != null && !targetControl.IsDisposed)
            {
                targetControl.Invalidate();
            }
        }

        /// <summary>
        /// 触发动画完成事件
        /// </summary>
        private void OnAnimationCompleted(Animation animation)
        {
            if (AnimationCompleted != null)
            {
                AnimationCompleted(this, new AnimationCompletedEventArgs(animation));
            }
        }

        /// <summary>
        /// 停止所有动画
        /// </summary>
        public void StopAllAnimations()
        {
            activeAnimations.Clear();
            animationTimer.Stop();
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (animationTimer != null)
            {
                animationTimer.Stop();
                animationTimer.Dispose();
            }
        }
    }

    /// <summary>
    /// 动画基类
    /// </summary>
    public abstract class Animation
    {
        public int Duration { get; protected set; }
        public int ElapsedTime { get; protected set; }
        public bool IsCompleted { get; protected set; }

        protected Animation(int duration)
        {
            Duration = duration;
            ElapsedTime = 0;
            IsCompleted = false;
        }

        public abstract void Update(int deltaTime);
        public abstract void Draw(Graphics g);
    }

    /// <summary>
    /// 方块移动动画
    /// </summary>
    public class BlockMoveAnimation : Animation
    {
        private Block block;
        private int startX, startY;
        private int targetX, targetY;
        private int currentX, currentY;

        public BlockMoveAnimation(Block block, int targetX, int targetY, int duration)
            : base(duration)
        {
            this.block = block;
            this.startX = block.X;
            this.startY = block.Y;
            this.targetX = targetX;
            this.targetY = targetY;
            this.currentX = startX;
            this.currentY = startY;
        }

        public override void Update(int deltaTime)
        {
            ElapsedTime += deltaTime;
            
            if (ElapsedTime >= Duration)
            {
                currentX = targetX;
                currentY = targetY;
                IsCompleted = true;
            }
            else
            {
                float progress = (float)ElapsedTime / Duration;
                // 使用缓动函数使动画更自然
                progress = EaseInOutQuad(progress);
                
                currentX = (int)(startX + (targetX - startX) * progress);
                currentY = (int)(startY + (targetY - startY) * progress);
            }
        }

        public override void Draw(Graphics g)
        {
            // 绘制移动中的方块
            var rect = new Rectangle(currentX * 80, currentY * 80, block.Width * 80, block.Height * 80);
            using (var brush = new SolidBrush(block.Color))
            {
                g.FillRectangle(brush, rect);
            }
            using (var pen = new Pen(Color.Black, 2))
            {
                g.DrawRectangle(pen, rect);
            }
        }

        private float EaseInOutQuad(float t)
        {
            return t < 0.5f ? 2 * t * t : -1 + (4 - 2 * t) * t;
        }
    }

    /// <summary>
    /// 方块选择动画
    /// </summary>
    public class BlockSelectAnimation : Animation
    {
        private Block block;
        private float alpha = 1.0f;

        public BlockSelectAnimation(Block block, int duration)
            : base(duration)
        {
            this.block = block;
        }

        public override void Update(int deltaTime)
        {
            ElapsedTime += deltaTime;
            
            if (ElapsedTime >= Duration)
            {
                IsCompleted = true;
            }
            else
            {
                float progress = (float)ElapsedTime / Duration;
                alpha = 0.5f + 0.5f * (float)Math.Sin(progress * Math.PI * 4); // 闪烁效果
            }
        }

        public override void Draw(Graphics g)
        {
            // 绘制选择高亮效果
            var rect = new Rectangle(block.X * 80, block.Y * 80, block.Width * 80, block.Height * 80);
            using (var brush = new SolidBrush(Color.FromArgb((int)(255 * alpha), Color.Yellow)))
            {
                g.FillRectangle(brush, rect);
            }
        }
    }

    /// <summary>
    /// 胜利动画
    /// </summary>
    public class VictoryAnimation : Animation
    {
        private List<Point> particles;
        private Random random;

        public VictoryAnimation(int duration)
            : base(duration)
        {
            this.particles = new List<Point>();
            this.random = new Random();
            
            // 创建粒子效果
            for (int i = 0; i < 50; i++)
            {
                particles.Add(new Point(random.Next(0, 400), random.Next(0, 500)));
            }
        }

        public override void Update(int deltaTime)
        {
            ElapsedTime += deltaTime;
            
            if (ElapsedTime >= Duration)
            {
                IsCompleted = true;
            }
            else
            {
                // 更新粒子位置
                for (int i = 0; i < particles.Count; i++)
                {
                    var particle = particles[i];
                    particle.Y -= 2; // 向上移动
                    particle.X += random.Next(-1, 2); // 随机左右移动
                    particles[i] = particle;
                }
            }
        }

        public override void Draw(Graphics g)
        {
            // 绘制粒子效果
            float progress = (float)ElapsedTime / Duration;
            int alpha = (int)(255 * (1 - progress));
            
            using (var brush = new SolidBrush(Color.FromArgb(alpha, Color.Gold)))
            {
                foreach (var particle in particles)
                {
                    g.FillEllipse(brush, particle.X, particle.Y, 4, 4);
                }
            }
        }
    }

    /// <summary>
    /// 动画完成事件参数
    /// </summary>
    public class AnimationCompletedEventArgs : EventArgs
    {
        public Animation Animation { get; private set; }

        public AnimationCompletedEventArgs(Animation animation)
        {
            Animation = animation;
        }
    }
} 